import React, { useState } from 'react';
import {
  Box,
  Button,
  TextField,
  Typography,
  Alert,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import { Product, NetWorthRecord } from '../../types/product';
import { saveProduct } from '../../services/storage';
import { crawlNetWorthData } from '../../services/netWorthCrawler';

interface NetWorthCrawlerProps {
  product: Product;
  onClose: () => void;
  onSuccess: () => void;
}

const NetWorthCrawler: React.FC<NetWorthCrawlerProps> = ({
  product,
  onClose,
  onSuccess,
}) => {
  const [url, setUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [previewData, setPreviewData] = useState<NetWorthRecord[]>([]);
  const [bankType, setBankType] = useState<'BOC' | 'CCB' | 'ICBC'>('BOC');

  const handleCrawl = async () => {
    if (!url) {
      setError('请输入数据源URL');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const records = await crawlNetWorthData({
        url,
        productCode: product.id,
        bankName: bankType,
      });

      if (records.length === 0) {
        setError('未找到有效的净值数据');
        return;
      }

      setPreviewData(records);

    } catch (err) {
      setError(err instanceof Error ? err.message : '抓取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleConfirm = () => {
    if (previewData.length === 0) {
      setError('没有可导入的数据');
      return;
    }

    try {
      // 更新产品数据
      const updatedProduct: Product = {
        ...product,
        netWorthHistory: [
          ...product.netWorthHistory,
          ...previewData.filter(
            newRecord => !product.netWorthHistory.some(
              existing => existing.date === newRecord.date
            )
          )
        ].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()),
        updatedAt: new Date(),
      };

      // 更新最新净值信息
      const latestRecord = previewData[0];
      if (latestRecord && new Date(latestRecord.date) > new Date(product.netWorthDate)) {
        updatedProduct.netWorth = latestRecord.value;
        updatedProduct.netWorthDate = latestRecord.date;
      }

      saveProduct(updatedProduct);
      onSuccess();
      onClose();
    } catch (err) {
      setError('保存数据失败');
    }
  };

  return (
    <Dialog open={true} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>抓取净值数据</DialogTitle>
      <DialogContent>
        <Box mt={2}>
          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          )}

          <Box mb={2}>
            <Typography variant="subtitle2" gutterBottom>
              选择银行
            </Typography>
            <Box display="flex" gap={2}>
              <Button 
                variant={bankType === 'BOC' ? 'contained' : 'outlined'}
                onClick={() => setBankType('BOC')}
                disabled={loading}
              >
                中国银行
              </Button>
              <Button 
                variant={bankType === 'CCB' ? 'contained' : 'outlined'}
                onClick={() => setBankType('CCB')}
                disabled={loading}
              >
                建设银行
              </Button>
              <Button 
                variant={bankType === 'ICBC' ? 'contained' : 'outlined'}
                onClick={() => setBankType('ICBC')}
                disabled={loading}
              >
                工商银行
              </Button>
            </Box>
          </Box>

          <Box mb={3}>
            <TextField
              fullWidth
              label="数据源URL"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              placeholder="请输入银行理财产品净值数据页面URL"
              disabled={loading}
              helperText="例如: https://www.bankofchina.com/sdbapp/wmpnetworth/xxxxx.html"
            />
          </Box>

          <Button
            variant="contained"
            onClick={handleCrawl}
            disabled={loading || !url}
            sx={{ mb: 3 }}
          >
            {loading ? <CircularProgress size={24} /> : '获取数据'}
          </Button>

          {previewData.length > 0 && (
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                预览数据 (共 {previewData.length} 条)
              </Typography>
              <Box sx={{ maxHeight: 300, overflowY: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr>
                      <th style={{ padding: 8, textAlign: 'left' }}>日期</th>
                      <th style={{ padding: 8, textAlign: 'right' }}>净值</th>
                    </tr>
                  </thead>
                  <tbody>
                    {previewData.map((record) => (
                      <tr key={record.id}>
                        <td style={{ padding: 8 }}>{record.date}</td>
                        <td style={{ padding: 8, textAlign: 'right' }}>
                          {record.value.toFixed(4)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </Box>
            </Box>
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>取消</Button>
        <Button
          variant="contained"
          onClick={handleConfirm}
          disabled={loading || previewData.length === 0}
        >
          导入数据
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default NetWorthCrawler;